# == Schema Info
# Schema version: 20091029102158
#
# Table name: posts
#
#  id              :integer(4)      not null, primary key
#  structure_id    :integer(4)
#  user_id         :integer(4)
#  brief           :text
#  cached_tag_list :string(255)
#  comments_count  :integer(4)      default(0)
#  content         :text(16777215)  not null, default("")
#  is_visible      :boolean(1)      default(TRUE)
#  language        :integer(1)      default(0)
#  slug            :string(50)
#  title           :string(255)     not null
#  created_at      :datetime
#  updated_at      :datetime

class Post < ActiveRecord::Base
  include HeaderTools
  
  acts_as_calendar :created_at
  acts_as_taggable_on :tags
  
  translates :title, :content, :brief
  
  validates_presence_of :title, :content
  validates_numericality_of :position, :only_integer => true
  
  acts_as_enum :language, AVAILABLE_LOCALES.map(&:to_sym)
  
  acts_as_uploaded :photo, :slider
  
  has_one :photo, :as=>:assetable, :dependent=>:destroy
  has_one :slider, :class_name=> "AttachmentFile", :as=>:assetable, :dependent=>:destroy
  belongs_to :user
  belongs_to :structure, :counter_cache=>true
  has_many :photos, :as=>:assetable, :dependent=>:destroy
  has_many :comments, :as => :commentable, :dependent => :destroy, :order=>"id ASC"
  has_slug
  
  attr_protected :user_id, :cached_tag_list
  
  default_scope :order => "position"
  named_scope :visible, :conditions=>{:is_visible=>true}
  named_scope :by_locale, lambda { |*args| {:conditions => ["language = ?", self.language(args.first.to_sym)] } }
  
  def category_title
    self.structure.try(:title)
  end
  
  def keywords
    @keywords ||= Nokogiri::HTML(self.content).to_s.strip.words_count.sort{|a,b| b[1]<=>a[1]}.select{ |k, v| k.strip.length > 8 }.map(&:first).slice(0, 5)
    @keywords
  end
end
